from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView
from django.contrib import messages
from django.http import JsonResponse
from .models import Order, OrderItem
from restaurants.models import MenuItem
from django.db.transaction import atomic

class OrderListView(LoginRequiredMixin, ListView):
    model = Order
    template_name = 'orders/order_list.html'
    context_object_name = 'orders'
    paginate_by = 10

    def get_queryset(self):
        return Order.objects.filter(user=self.request.user).order_by('-created_at')

class OrderDetailView(LoginRequiredMixin, DetailView):
    model = Order
    template_name = 'orders/order_detail.html'
    context_object_name = 'order'

    def get_queryset(self):
        return Order.objects.filter(user=self.request.user)

@login_required
def add_to_cart(request):
    if request.method == 'POST':
        menu_item_id = request.POST.get('menu_item_id')
        quantity = int(request.POST.get('quantity', 1))
        
        try:
            menu_item = MenuItem.objects.get(id=menu_item_id, is_available=True)
            cart = request.session.get('cart', {})
            
            if menu_item_id in cart:
                cart[menu_item_id]['quantity'] += quantity
            else:
                cart[menu_item_id] = {
                    'quantity': quantity,
                    'price': float(menu_item.price)
                }
            
            request.session['cart'] = cart
            messages.success(request, '已添加到购物车')
            return JsonResponse({'success': True, 'cart_count': len(cart)})
            
        except MenuItem.DoesNotExist:
            return JsonResponse({'success': False, 'message': '菜品不存在或已下架'})
            
    return JsonResponse({'success': False, 'message': '无效的请求'})

@login_required
@atomic
def create_order(request):
    cart = request.session.get('cart', {})
    if not cart:
        messages.error(request, '购物车为空')
        return redirect('restaurant_list')
        
    try:
        # 创建订单
        order = Order.objects.create(
            user=request.user,
            status='pending'
        )
        
        # 创建订单项
        total_amount = 0
        for menu_item_id, item_data in cart.items():
            menu_item = MenuItem.objects.get(id=menu_item_id)
            quantity = item_data['quantity']
            price = item_data['price']
            
            OrderItem.objects.create(
                order=order,
                menu_item=menu_item,
                quantity=quantity,
                price=price
            )
            total_amount += quantity * price
        
        # 更新订单总金额
        order.total_amount = total_amount
        order.save()
        
        # 清空购物车
        request.session['cart'] = {}
        
        messages.success(request, '订单创建成功')
        return redirect('order_detail', pk=order.id)
        
    except Exception as e:
        messages.error(request, '创建订单失败，请重试')
        return redirect('cart')

@login_required
def cancel_order(request, order_id):
    order = get_object_or_404(Order, id=order_id, user=request.user)
    
    if order.status != 'pending':
        messages.error(request, '只能取消待处理的订单')
        return redirect('order_detail', pk=order.id)
        
    order.status = 'cancelled'
    order.save()
    messages.success(request, '订单已取消')
    return redirect('order_list')
